<template>
  <div style="padding:20px">
    <!-- 按钮开始-->
    <div>
      <el-button @click="toAdd" type="primary" size="mini">添加</el-button>
    </div>
    <!-- 按钮结束-->
    <!-- 表格开始 -->
    <div>
      <!-- {{tableData}} -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="80"></el-table-column>
        <el-table-column prop="id" label="栏目编号" width="220"></el-table-column>
        <el-table-column prop="name" label="名称" width="220"></el-table-column>
        <el-table-column prop="icon" label="图标" width="220">
          <template slot-scope="scope">
            <div>
              <el-popover placement="right" trigger="hover">
                <el-image slot="reference" style="width: 50px; height: 50px" :src="scope.row.icon"></el-image>
                <el-image style="width:200px; height: 200px" :src="scope.row.icon"></el-image>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="排序号" width="300"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text" size="small">编辑</el-button>
            <el-button type="text" size="small" @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 表格结束 -->
    <!-- 分页开始 -->
    <div style="text-align:right;margin:5px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 分页结束 -->
    <!-- 模态框开始 -->
    <el-dialog :title="title" :visible.sync="visible">
      <el-form :model="form" :rules="rules" ref='myForm'>
        <el-form-item label="栏目名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="序号" :label-width="formLabelWidth">
          <el-input v-model="form.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" :label-width="formLabelWidth" prop="icon">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="form.icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit('myForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 模态框结束 -->
  </div>
</template>
<script>
import { showFileURL, uploadFileURL } from "@/utils/config";
import { pageQuery, saveOrUpdate, deleteById } from "@/api/column";
export default {
  data() {
    return {
      // 校验表单
      rules: {
        name: [{ required: true, message: "请输入栏目名称", trigger: "blur" }],
        icon: [{ required: true, message: "请上传栏目图标", trigger: "blur" }]
      },
      imageUrl: "",
      // 图片显示的基础路径
      showFileURL,
      // 文件上传得文件
      uploadFileURL,
      // 表格绑定得数据
      tableData: [],
      // 双向数据绑定得表单
      form: {},
      // 控制表单控件宽度
      formLabelWidth: "80px",
      //控制模态框显示与隐藏
      visible: false,
      // 模态框title变量
      title: "",
      total: 0,
      params: {
        page: 1,
        pageSize: 5
      }
    };
  },
  watch: {
    params: {
      handler() {
        this.queryPage();
      },
      deep: true
    }
  },
  created() {
    this.queryPage();
  },
  methods: {
    // 给删除按钮绑定事件
    toDelete(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // 确定删除 发送删除请求
          let res = await deleteById({ id: id });
          this.queryPage();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          // 点击取消 提示用户取消删除
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 给确定按钮绑定事件 执行保存（新增--空）或者更新（修改--id）操作
    toSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 检验通过
          let res = await saveOrUpdate(this.form);
          this.visible = false;
          console.log(res);
          this.$message({
            message: res.message,
            type: "success"
          });
          // 刷新页面
          this.queryPage();
        } else {
          this.$message.error('保存失败');
          return false;
        }
      });
    },

    // 给编辑按钮绑定事件
    toEdit(row) {
      this.visible = true;
      this.title = "修改栏目信息";
      this.form = { ...row };
      this.imageUrl = this.form.icon;
    },
    // 给添加按钮绑定事件
    toAdd() {
      // 显示模态框
      this.visible = true;
      this.title = "添加栏目信息";
      this.form = {};
      this.imageUrl = "";
    },
    //   分页数据查询
    async queryPage() {
      let temp = {
        ...this.params
        //   page,
        //   pageSize,
      };
      let res = await pageQuery(temp);
      console.log(res);
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    // 处理每页显示得条数[5,10,15,20]
    handleSizeChange(pageSize) {
      //   console.log(`每页 ${val} 条`);
      this.params.pageSize = pageSize;
      // this.queryPage()
    },
    //   处理当前页
    handleCurrentChange(page) {
      //   console.log(`当前页: ${val}`);
      this.params.page = page;
      // this.queryPage()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(res);
      // 展示图片 图片基础路径+图片地址
      this.form.icon = showFileURL + res.data.id;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>
<style lang="scss">
</style>